package soccer.stats

import org.codehaus.groovy.grails.commons.ConfigurationHolder as CH
import com.singhanuvrat.soccerstats.Utils.JsoupUtils

class UpdateDataService {

    static transactional = true

    /**
     * Update the db with all the teams playing in a certain league
     * @param leagueNick (String) The nick of the league, epl for example.
     * @return The list of all the teams added to the db
     */
    static def updateTeamsInfo(leagueNick) {
        def league = CH.config.com.singhanuvrat.soccerstats.leagues[leagueNick]
        if(league == null) return []

        def newTeamsAdded = []
        JsoupUtils.getDocument(league.soccernetLeagueUrl).select("table[class=tablehead]").get(0).select("td:eq(1").each {
            def teamName = it.text()
            if (!Team.findByName(teamName)) {
                def team = new Team(name: teamName, teamType: league.participatingTeamTypes, country: league.country)
                team.save()

                def teamUrl = it.select("a[href]").attr("abs:href")
                new TeamInfoUrl(team: team, sourceType: 'soccernet', url: teamUrl).save()

                newTeamsAdded.add teamName
            }
        }
        return newTeamsAdded
    }

    /**
     * Given the list of teams, update the db with the list of all its players
     * @param teamNames (List<String>) The list of team names, [Chelsea, Arsenal] for example.
     * @return The map of teams and their players added to the db
     */
    static def updatePlayersInfo(teamNames) {
        def newPlayersAdded = [:]
        teamNames.each {teamName ->

        }
    }
}
